<?php

namespace pmvc\ioc;

use pmvc\Properties;

/**
 * Factory class for creating a Properties object.
 */
class PropertiesFactory
implements FactoryObject {

	private $addEnvironmentVariables 		= FALSE;
	private $environmentVariablesOverride	= FALSE;
	private $requiredPropertyFiles			= Array();
	private $optionalPropertyFiles			= Array();

	public function createObject() {
		$properties = new Properties();
		if (!$this->environmentVariablesOverride && $this->addEnvironmentVariables) {
			$this->addAllEnvironmentVariables($properties);
		}
		foreach ($this->requiredPropertyFiles as $propertyFile) {
			if (file_exists($propertyFile)) {
				$properties->loadFromFile($propertyFile);
			} else {
				throw new \Exception("Error loading required properties file: " . $propertyFile);
			}
		}
		foreach ($this->optionalPropertyFiles as $propertyFile) {
			if (file_exists($propertyFile)) {
				$properties->loadFromFile($propertyFile);
			}
		}
		if ($this->environmentVariablesOverride && $this->addEnvironmentVariables) {
			$this->addAllEnvironmentVariables($properties);
		}
		return $properties;
	}

	private function addAllEnvironmentVariables(Properties $properties) {
		if (isset($_ENV)) {
			$this->setValue($properties, "env", $_ENV);
		}
		if (isset($_SERVER)) {
			$this->setValue($properties, "server", $_SERVER);
		}
		if (isset($argv)) {
			$this->setValue($properties, "argv", $argv);
		}
		$this->setValue($properties, "ini", ini_get_all());
	}

	private function setValue(Properties $properties, $baseName, $value) {
		if (!is_array($value)) {
			$properties->setProperty($baseName, $value);
		} else {
			foreach ($value as $key => $val) {
				$this->setValue($properties, $baseName.".".$key, $val);
			}
		}
	}

	public function setAddEnvironmentVariables($addEnvironmentVariables) {
		$this->addEnvironmentVariables = $addEnvironmentVariables;
	}

	public function setEnvironmentVariablesOverride($environmentVariablesOverride) {
		$this->environmentVariablesOverride = $environmentVariablesOverride;
	}

	public function setRequiredPropertyFiles($requiredPropertyFiles) {
		$this->requiredPropertyFiles = $requiredPropertyFiles;
	}

	public function setOptionalPropertyFiles($optionalPropertyFiles) {
		$this->optionalPropertyFiles = $optionalPropertyFiles;
	}
}

?>